package com.test.aidldemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;


import java.util.Timer;
import java.util.TimerTask;

public class AidlService extends Service {


    private CatBinder catBinder;

    private Timer timer = new Timer();
    private String[] colors = new String[]{"红色","黄色","黑色","白色"};
    private double[] weights = new double[]{2.3, 3.1, 1.28,1.58};
    private String color;
    private double weight;

    @Override
    public void onCreate() {
        super.onCreate();
        catBinder = new CatBinder();
        Log.e("1212", "onCreate: " + "创建service" );
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //随机改变Service组件内的color weight属性的值
                int rand = (int)((Math.random() * 4));
                color = colors[rand];
                weight = weights[rand];
            }
        },0 , 800);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        /**
         *
         * 返回catBinder对象,
         * 在绑定本地Service时:该 catBinder 对象会直接传递给客户端的ServiceConnection,的onServiceConnected方法的第二个参数
         *
         * 绑定远程Service:只是将 catBinder 对象的代理传递给客户端的ServiceConnection,的onServiceConnected方法的第二个参数
         */
        return catBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    class CatBinder extends ICat.Stub{

        @Override
        public String getColor() throws RemoteException {
            return AidlService.this.color;
        }

        @Override
        public double getWeight() throws RemoteException {
            return AidlService.this.weight;
        }
    }
}
